package com.demo.webflux.dubbo;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.apache.dubbo.rpc.RpcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.demo.DemoService;
import com.alibaba.dubbo.demo.Student;

import reactor.core.publisher.Mono;

@Component
public class DubboClientService implements BeanFactoryAware {
	private static Logger logger = LoggerFactory.getLogger(DubboClientService.class);
	private BeanFactory beanFactory;

	public Student saveUser(Student st) throws InterruptedException, ExecutionException{
		DemoService demoService = (DemoService) beanFactory.getBean("demoService2");

		demoService.sayHello(st);
        Future<Student> f1 = RpcContext.getContext().getFuture();
        logger.info("阻塞");
		return f1.get();
	}

	public Mono<Student> saveUserAsync(Student st) {
		return Mono.create(sink -> {
			try {
				RpcContext.getContext().set("SINK", sink);
				DemoService demoService = (DemoService) beanFactory.getBean("demoService3");
				demoService.sayHello(st);
			} catch (Exception e) {
				e.printStackTrace();
			}
        });
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

}
